package com.shirley.pers.zhufengfmvi.utils;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Description: IO流的工具类<br/>
 * <p/>
 * Copyright (c) , 2016, Shirley Xian <br/>
 * This program is protected by copyright laws. <br/>
 * ClassName: StreamUtils<br/>
 * Date: 2016/4/6 10:32
 *
 * @author Shirley Xian
 * @version 1.0
 */
public final class StreamUtils {
    private StreamUtils() {
    }

    public static byte[] readStream(InputStream inputStream) {
        byte[] bytes = null;
        if (inputStream != null) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            readStream(inputStream, bout);
            bytes = bout.toByteArray();
            close(bout);
        }
        return bytes;
    }

    public static long readStream(InputStream is, OutputStream os) {
        long ret = 0;
        if (is != null && os != null) {
            byte[] buf = new byte[1 << 10];
            int len;
            try {
                while (true) {
                    len = is.read(buf);
                    if (len == -1) {
                        break;
                    }
                    os.write(buf, 0, len);
                    ret += len;
                }
            } catch (IOException e) {
                e.printStackTrace();
                ret = -1;
            }
            //当请求量非常大的时候，那么网络请求次数非常多的时候
            //即时很大的字节的数组，频繁的创建，也会导致内存的溢出
            buf = null;
        }
        return ret;
    }

    /**
     * 关闭IO流
     * @param stream java中，对于所有的IO流，都让这些类实现Closeable接口
     *               这个接口只有一个方法，叫做close()，就是用于关流的e
     */
    public static void close(Closeable stream){
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

